<?php
//header("Content-type: text/plain");


/**
 * http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid
 * http://www.php.net/manual/en/function.uniqid.php#94959
 * http://club.shelek.ru/viewart.php?id=307#post_classic
 *
 * Sticky footer:
 * http://stackoverflow.com/questions/42294/how-do-you-get-the-footer-to-stay-at-the-bottom-of-a-web-page
 */

/**                              --- DONE ---
 * + secure storage (AES) 01/06/12
 * + messages adding      01/06/12
 */

/**                             --- ROADMAP ---
 * - messages editing
 * - messages tree loadin at once
 * - JSON compressing
 * - Stick search bar at top after scrolling
 * http://blog.yjl.im/2010/01/stick-div-at-top-after-scrolling.html
 *
 */



# the response from reCAPTCHA
//$resp = null;
# the error code from reCAPTCHA, if any
//$error = null;


//$uid = gen_uid(8);

// probability for $len = 8 is 1/218340105584896 (~4.58-15e),
//xdbg()->info($uid, strlen($uid), mt_rand(0, 3));

if (!array_key_exists('method', $_POST) || !array_key_exists('args', $_POST)) {
    header('Location: ./');
} else {
    $method = $_POST['method'];
    $args = $_POST['args'];
}


require_once('./settings.php');
require_once('./php/routines.php');
require_once('./php/messages.php');
require_once('../experiments/lib.dbg.php');






init_db($dsn, $user, $password, $options);

usleep(300000);    // emulate normal lag
//sleep(5);    // emulate HARD lag

function amber_check_param($args, $name) {
    if (is_array($name)) {
        foreach ($name as $n) {
            amber_check_param($args, $n);
        }
        return;
    }

    //    var_dump($name);
    if(!array_key_exists($name, $args)) {
        if (xdbg()->can_debug()) {
            amber_send_error('Something wrong with passed arguments (' + $name + ')' );
        } else {
            amber_send_data(array());
        }
    }
}

if ('get_message' == $method) {
    amber_check_param($args, 'id');
    $res = amber_get_message($args['id']);
    if (!sizeof($res['resp'])) {
        amber_send_error('No such entry found');
    }
    amber_send_data($res);
    //} elseif ('get_children' == $method) {
    //    amber_check_param($args, 'id');
    //    amber_send_data(amber_get_children($args['id']));
    //} elseif ('get_messages_tree' == $method) {
    //    amber_check_param($args, 'ids');
    //
    //    $ids = explode('-', $args['ids']);
    //
    //    if (!$ids) {
    //        amber_send_data(array());
    //    }

} elseif ('create_new_message' == $method) {
    amber_check_param($args, array('expire', 'nickname', 'superkey', 'message',
                                'secresp', 'worldkey', 'secstorage', 'secret'));

    $args['secresp']    = (bool) $args['secresp'];
    $args['secstorage'] = (bool) $args['secstorage'];

    amber_send_data(
    amber_create_new_message($args['expire'],
    $args['nickname']
    ? $args['nickname']
    : amber_gen_nickname(),
    $args['superkey']
    ? $args['superkey']
    : gen_uid(AMBER_KEY_LEN),
    $args['message'],
    $args['secresp']
    ? ($args['worldkey']
    ? $args['worldkey']
    : gen_uid(AMBER_KEY_LEN))
    : NULL,
    $args['secstorage']
    ? $args['secret']
    : NULL
    )
    );
} else {
    amber_send_error('Access denied');
}

function amber_create_new_message($expire, $nickname, $superkey, $message, $worldkey, $secret) {
    $id = gen_uid(AMBER_ID_LEN);
    $options = 0;

    if (NULL !== $secret) {
        $options |= AMBER_OPT_CRYPT;
        $message = amber_encrypt_string($message, $secret);
    }

    $sql = "
    	INSERT INTO `amber_messages` (`id`, `thread_id`,	`parent_id`, `full_path`, `created`, `updated`, `expire`,	`message`, `options`, `superkey`, `worldkey`, `nickname`)
    		 VALUES                  (:id,  :id,             NULL,       '',          :created,  :created,   :expire,	:message,  :options,  :superkey,  :worldkey,  :nickname)
    ";


    $args = array (
        ':id' => $id,
        ':created' => microtime(TRUE),
        ':expire' => $expire,
        ':message' => $message,
        ':options' => $options,
        ':superkey' => amber_hash_password($superkey),
        ':worldkey' => NULL === $worldkey ? NULL : amber_hash_password($worldkey),
        ':nickname' => $nickname
    );

    $res = amber_run_query($sql, $args, FALSE);

    if (23000 == $res) {
        $id = gen_uid(AMBER_ID_LEN);
        $args[':id'] = $id;

        $res = amber_run_query($sql, $args, FALSE);

        if (23000 == $res) {
            $id = gen_uid(AMBER_ID_LEN);
            $args[':id'] = $id;
            $res = amber_run_query($sql, $args, FALSE);

            if (23000 == $res) {
                amber_send_error('Server is busy, please, try again later');
                return ;
            }
        }
    }


    $msg = amber_get_message($id);

    if (!sizeof($msg['resp'])) {
        amber_send_error('Your message was added, but it could not be found, probably, it is expired.');
        return ;
    }

    return array(
        'resp'  => $msg['resp'],
        'info' => array('superkey' => $superkey,
            		    'nickname' => $nickname,
                        'worldkey' => $worldkey,
                        'secret'   => $secret
    ),
    );
}


//function amber_get_messages_tree($ids) {
//    $res = array();
//
//
//    do {
//        $id = array_pop($ids);
//        $parent = amber_run_query($sql, array(':id' => $id));
//    } while (!$parent && $ids);
//
//    if (!$parent) {
//        amber_send_data(array());
//    }
//
//    foreach ($array_expression as $value) {
//        ;
//    }
//
//}






?>